<template>
  <div class="container">
    <el-row :gutter="50">
      <!-- 左侧树 -->
      <el-col :span="8">
        <div class="hd">
          <h4 class="title">省市区列表</h4>
          <el-button
              size="mini"
              type="primary"
              icon="el-icon-plus"
              class="handle-del mr10"
              @click="handleAdd"
              v-if="$perm.hasPerm('button_region_add')"
          >添加
          </el-button>
        </div>

        <!-- 树 -->
        <TreeData
            ref="treeRef"
            :data="regionList"
            :props="defaultProps"
            :default-expand-all="false"
            isSlot
        >
          <template #default="{ node, data }">
            <div class="menu-item">
              <div class="label">{{ node.label }}</div>
              <div class="operate">
                <i
                    class="el-icon-plus"
                    style="margin-left:20px"
                    @click.stop="handleAddChild(data)"
                    v-if="$perm.hasPerm('button_region_add')"
                />
                <i
                    class="el-icon-edit"
                    style="margin-left:20px"
                    @click.stop="handleEditItem(data)"
                    v-if="$perm.hasPerm('button_region_edit')"
                />
                <i
                    class="el-icon-delete"
                    style="margin-left:20px;color: red"
                    @click.stop="handleRemove(data)"
                    v-if="$perm.hasPerm('button_region_batchDelete')"
                />
              </div>
            </div>
          </template>
        </TreeData>
      </el-col>

      <!-- 右侧表单 -->
      <el-col :span="16">
        <div class="hd">
          <h4 class="title">{{ operateTitle }}</h4>
        </div>
        <div v-if="operateTitle" class="form-box">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-input v-if="visible" v-model="form.parentId" />
            <el-form-item label="名称" prop="name">
              <el-input
                  v-model="form.name"
                  placeholder="请输入名称"
                  clearable
                  size="small"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                  v-model="form.status"
                  placeholder="请填写状态"
                  class="handle-select mr10"
                  clearable
              >
                <el-option
                    v-for="item in $enum.getMapItems('status')"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input
                  v-model="form.remark"
                  placeholder="请填写备注"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  maxlength="99"
                  show-word-limit
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="saveEdit">确定</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import TreeData from '@/components/common/TreeData'
import {
  regionDetailApi,
  regionEditApi,
  regionListAllApi,
  regionRemoveApi,
  regionSaveApi
} from '@/api/setup/region'
import { createObjectBase, deepCopy } from '@/utils'

const rawObj = {
  id: '',
  name: '',
  parentId: null,
  status: '',
  remark: ''
}

export default {
  name: 'RegionMgt',
  components: { TreeData },
  data() {
    return {
      visible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      form: deepCopy(rawObj),
      regionList: [],
      operateTitle: '添加一级的省',
      rules: {
        name: [
          { required: true, message: '请填写名称', trigger: 'blur' },
          { max: 20, message: '长度不超过20', trigger: 'blur' }
        ],
        remark: [
          { max: 99, message: '长度不超过99', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    /* 获取省市区树 */
    async getData() {
      const res = await regionListAllApi()
      this.regionList = res?.bizData || []
    },
    /* 新增一级 */
    handleAdd() {
      this.resetForm()
      this.operateTitle = '添加一级的省'
      this.form.parentId = null
    },
    /* 新增子级 */
    handleAddChild(item) {
      this.resetForm()
      this.operateTitle = `添加【${item.name}】的子集`
      this.form.parentId = item.id
    },
    /* 编辑 */
    async handleEditItem(item) {
      this.resetForm()
      this.operateTitle = `编辑【${item.name}】`
      const res = await regionDetailApi({ id: item.id })
      this.form = createObjectBase(res?.bizData, Object.keys(rawObj))
    },
    /* 删除 */
    handleRemove(item) {
      this.$confirm(`确定删除【${item.name}】吗？`, '提示', { type: 'warning' })
          .then(async() => {
            await regionRemoveApi({ ids: item.id })
            this.$message.success('删除成功')
            await this.getData()
          })
          .catch(() => {})
    },
    /* 保存 */
    saveEdit() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        const data = createObjectBase(this.form, Object.keys(rawObj))
        if (data.parentId === '') data.parentId = null
        const fn = data.id ? regionEditApi : regionSaveApi
        await fn(data)
        this.$message.success('保存成功')
        this.resetForm()
        await this.getData()
      })
    },
    /* 重置表单 */
    resetForm() {
      this.form = deepCopy(rawObj)
      this.$nextTick(() => {
        if (this.$refs.form) this.$refs.form.clearValidate()
      })
    }
  }
}
</script>

<style scoped>
.ml10 { margin-left: 10px; margin-right: 10px; }
.hd {
  display: flex;
  padding-bottom: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.title {
  flex: 1;
  color: #464646;
  font-size: 24px;
  font-weight: bold;
}
.menu-item {
  display: flex;
  flex: 1;
  align-items: center;
}
.menu-item .label {
  flex: 1;
  color: #666;
  font-size: 14px;
}
.menu-item .operate {
  color: #409eff;
  font-size: 14px;
}
.menu-item .operate i {
  margin-left: 20px;
  cursor: pointer;
}
.menu-item .operate .el-icon-delete { color: #f56c6c; }
.form-box { width: 400px; }
</style>
